package com.example.shutdown_v1.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 短信通知服务
 * 负责发送告警短信给店铺责任人
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsNotificationService {

    @Value("${sms.enabled:false}")
    private boolean smsEnabled;
    
    @Value("${sms.provider:aliyun}")
    private String smsProvider; // aliyun, tencent, huawei
    
    @Value("${sms.access-key:}")
    private String accessKey;
    
    @Value("${sms.access-secret:}")
    private String accessSecret;
    
    @Value("${sms.sign-name:三关一闭监控系统}")
    private String signName;
    
    @Value("${sms.template-code:}")
    private String templateCode;

    /**
     * 发送未关闭开关告警短信
     * @param shopName 店铺名称
     * @param responsiblePerson 责任人姓名
     * @param phoneNumber 手机号码
     * @param unclosedSwitches 未关闭的开关列表
     * @return 是否发送成功
     */
    public boolean sendUnclosedSwitchAlarm(String shopName, String responsiblePerson, 
                                          String phoneNumber, List<String> unclosedSwitches) {
        if (!smsEnabled) {
            log.info("[短信模拟] 店铺={}, 责任人={}, 手机={}, 未关闭开关={}", 
                    shopName, responsiblePerson, phoneNumber, unclosedSwitches);
            return false;
        }
        
        try {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
            String content = buildSmsContent(shopName, time, unclosedSwitches);
            
            boolean success = sendSms(phoneNumber, content);
            
            if (success) {
                log.info("[短信已发送] 手机={}, 店铺={}, 未关闭数={}", 
                        maskPhone(phoneNumber), shopName, unclosedSwitches.size());
            } else {
                log.error("[短信发送失败] 手机={}, 店铺={}", 
                        maskPhone(phoneNumber), shopName);
            }
            
            return success;
            
        } catch (Exception e) {
            log.error("[短信发送异常] 手机={}, 店铺={}", maskPhone(phoneNumber), shopName, e);
            return false;
        }
    }

    /**
     * 发送低电量告警短信
     */
    public boolean sendLowBatteryAlarm(String shopName, String phoneNumber, 
                                      String sensorId, int batteryLevel) {
        if (!smsEnabled) {
            log.info("[短信模拟] 低电量告警: 店铺={}, 传感器={}, 电量={}%", 
                    shopName, sensorId, batteryLevel);
            return false;
        }
        
        try {
            String content = String.format(
                    "【%s】您好！店铺[%s]的传感器[%s]电量过低（%d%%），请及时更换电池。", 
                    signName, shopName, sensorId, batteryLevel);
            
            return sendSms(phoneNumber, content);
            
        } catch (Exception e) {
            log.error("[短信发送异常] 低电量告警", e);
            return false;
        }
    }

    /**
     * 发送传感器离线告警短信
     */
    public boolean sendSensorOfflineAlarm(String shopName, String phoneNumber, 
                                         String sensorId) {
        if (!smsEnabled) {
            log.info("[短信模拟] 传感器离线: 店铺={}, 传感器={}", shopName, sensorId);
            return false;
        }
        
        try {
            String content = String.format(
                    "【%s】您好！店铺[%s]的传感器[%s]已离线，请检查设备连接。", 
                    signName, shopName, sensorId);
            
            return sendSms(phoneNumber, content);
            
        } catch (Exception e) {
            log.error("[短信发送异常] 离线告警", e);
            return false;
        }
    }

    /**
     * 构建短信内容
     */
    private String buildSmsContent(String shopName, String time, List<String> unclosedSwitches) {
        StringBuilder content = new StringBuilder();
        content.append("【").append(signName).append("】");
        content.append("您好！店铺[").append(shopName).append("]在 ");
        content.append(time).append(" 检测到以下设备未关闭：\n");
        
        int count = 0;
        for (String switchInfo : unclosedSwitches) {
            if (count >= 3) { // 短信长度限制，最多显示3个
                content.append("等共").append(unclosedSwitches.size()).append("个设备");
                break;
            }
            content.append("- ").append(switchInfo).append("\n");
            count++;
        }
        
        content.append("请及时处理！");
        return content.toString();
    }

    /**
     * 实际发送短信（模拟模式）
     */
    private boolean sendSms(String phoneNumber, String content) {
        // 短信功能暂不集成，仅作模拟记录
        
        log.info("📱 [短信发送] 手机={}, 内容={}", maskPhone(phoneNumber), content);
        
        // 模拟发送（实际环境需要替换为真实SDK调用）
        switch (smsProvider.toLowerCase()) {
            case "aliyun":
                return sendByAliyun(phoneNumber, content);
            case "tencent":
                return sendByTencent(phoneNumber, content);
            case "huawei":
                return sendByHuawei(phoneNumber, content);
            default:
                log.warn("未配置短信服务商，当前为模拟模式");
                return false;
        }
    }

    /**
     * 阿里云短信发送（模拟模式）
     */
    private boolean sendByAliyun(String phoneNumber, String content) {
        log.debug("[阿里云短信] 模拟发送成功");
        return true;
    }

    /**
     * 腾讯云短信发送（模拟模式）
     */
    private boolean sendByTencent(String phoneNumber, String content) {
        log.debug("[腾讯云短信] 模拟发送成功");
        return true;
    }

    /**
     * 华为云短信发送（模拟模式）
     */
    private boolean sendByHuawei(String phoneNumber, String content) {
        log.debug("[华为云短信] 模拟发送成功");
        return true;
    }

    /**
     * 手机号码脱敏
     */
    private String maskPhone(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() < 11) {
            return phoneNumber;
        }
        return phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
    }

    /**
     * 验证手机号格式
     */
    public boolean isValidPhone(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }
        // 简单的中国手机号验证
        return phoneNumber.matches("^1[3-9]\\d{9}$");
    }
}

